<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarDateDao;
use app\model\car\CarDate;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * Class CarDateServices
 * @package app\services\shendeng
 */
class CarDateServices extends BaseServices
{
    public function __construct(CarDateDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page,$limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        foreach ($list['list'] as &$item){
            $item['book_date'] = date('Y-m-d',$item['book_date']);
        }
        return $list;
    }

    /**
     * 添加
     * @param $data
     * @param $op_user
     * @param $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add($data,$op_user,$op_user_type){
        // 判断用户选择了星期几
        $date = [];
        foreach ($data['day'] as $day){
            if($day == 'mon'){
                $date[] = 'Monday';
            } else if($day == 'tue'){
                $date[] = 'Tuesday';
            } else if($day == 'wed'){
                $date[] = 'Wednesday';
            } else if($day == 'thu'){
                $date[] = 'Thursday';
            } else if($day == 'fri'){
                $date[] = 'Friday';
            } else if($day == 'sat'){
                $date[] = 'Saturday';
            } else if($day == 'sun'){
                $date[] = 'Sunday';
            }
        }
        $time = $data['book_date'];
        $time0 = strtotime($time[0]);
        if(strtotime("+1 day",$time0)<=time()){
            throw new AdminException('开始时间不得早于当前时间');
        }
        // 如果没有第二个时间段
        if(empty($time[1])){
            $time[1] = $time0;
        }
        $arr = [];
        foreach ($date as $item){
            for($i = strtotime($item,strtotime($time[0]));$i <= strtotime($time[1]);$i = strtotime('+1 week',$i)){
                $arr[] = $i;
            }
        }
        $result = false;
        while($time0 <= strtotime($time[1])){
            if(in_array($time0,$arr)){
                $insert['type_id'] = $data['type_id'];
                $insert['price_hour'] = $data['price_hour'];
                $insert['price'] = $data['price'];
                $insert['book_date'] = $time0;
                $insert['add_time'] = time();
                $where=[
                    ['book_date','=',$time0],
                    ['type_id','=',$data['type_id']]
                ];
                $cover = Db::name('car_date')->where($where)->find();
                if(!empty($cover)){
                    $result = CarDate::update($insert,['id'=>$cover['id']]);
                    $obj_id = $cover['id'];
                    $title = '每日价格编辑【'.$cover['id'].'】';
                    $operation_type = 11;
                }else{
                    $result = CarDate::create($insert);
                    $obj_id = $result->id;
                    $title = '每日价格添加【'.$obj_id.'】';
                    $operation_type = 10;
                }
                BaseLogServices::addLog($obj_id,3,$title,$op_user_type,$op_user['id'],$op_user['real_name'],$operation_type);
            }
            $time0=strtotime ("+1 day",$time0);
        }
        if($result) {
            return ('添加成功');
        } else {
            throw new AdminException('添加失败，没有符合条件的数据');
        }
    }

    /**
     * 编辑
     * @param $data
     * @param $op_user
     * @param $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($data,$op_user,$op_user_type){
        if(strtotime("+1 day",strtotime($data['edit_date']))<=time()){
            throw new AdminException('开始时间不得早于当前时间');
        }
        $where = [
            ['book_date','=',strtotime($data['edit_date'])],
            ['type_id','=',$data['type_id']],
        ];
        $date = Db::name('car_date')->where($where)->find();
        if($date && $date['id'] !== (int)$data['id']){ // 如果当前城市当前车型在这一天中已存在删掉旧数据保留当前数据
            throw new AdminException('该城市当天已存在该车型价格，ID为'.$date['id']);
        }else{
            $data['book_date'] = strtotime($data['edit_date']);
            $res = CarDate::update($data,['id'=>$data['id']]);
            if($res){
                $title = '每日价格编辑【'.$data['id'].'】';
                BaseLogServices::addLog($data['id'],3,$title,$op_user_type,$op_user['id'],$op_user['real_name'],11);
                return '编辑成功';
            }else{
                throw new AdminException('编辑失败或你什么也没有编辑!');
            }
        }
    }

    /**
     * 删除
     * @param $ids
     * @param $op_user
     * @param $op_user_type
     * @return string
     */
    public function dateDelete($ids,$op_user,$op_user_type){
        $id = join(',',$ids);
        $res = CarDate::where('id','in',$id)->delete();
        if($res){
            $title = '批量删除每日价格【'.$id.'】';
            BaseLogServices::addLog(0,3,$title,$op_user_type,$op_user['id'],$op_user['real_name'],12);
            return '删除成功';
        }else{
            throw new ValidateException('删除失败或你未选择数据');
        }
    }

    /**
     * 删除
     * @param int $id
     * @param $op_user
     * @param $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delDate(int $id,$op_user,$op_user_type){
        $date = $this->dao->get($id);
        $res = CarDate::where('id','=',$id)->delete();
        if($res){
            $title = '删除每日价格【'.$id.'】';
            BaseLogServices::addLog($id,3,$title,$op_user_type,$op_user['id'],$op_user['real_name'],12);
            return '删除成功';
        }else{
            throw new AdminException('删除失败');
        }
    }

    /**
     * 展示价格日历
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPriceCalendar($data){
        $today = strtotime(date('Y-m-d',time()));
        $one_year_today = strtotime("+2 year",$today);
        $list_data = [];
        while ($today <= $one_year_today){
            $temp['year'] = (int)date('Y',$today);
            $temp['month'] = (int)date('m',$today);
            $month_start = strtotime(date('Y-m-01', $today));
            $month_end = strtotime(date('Y-m-t',$today));
            $day = 0;
            $day_temp = [];
            $car_date = CarDate::field('book_date,price')->where(['type_id'=>$data['type_id']])->whereMonth('book_date',date('Y-m',$today))->select();
            $car_date = $car_date ? $car_date->toArray() : [];
            while ($month_start <= $month_end){
                $day = $day+1;
                $is_price = false;
                $week = (int)date('w',$month_start);
                if($car_date){
                    foreach ($car_date as $item){
                        if($item['book_date'] == $month_start){
                            $price = $item['price'];
                            $is_price = true;
                            unset($item);
                            break;
                        }
                    }
                    if(!$is_price){
                        if($week == 6){
                            $price = $data['sat_price'];
                        }else if($week == 0){
                            $price = $data['sun_price'];
                        }else{
                            $price = $data['price'];
                        }
                    }
                }else{
                    if($week == 6){
                        $price = $data['sat_price'];
                    }else if($week == 0){
                        $price = $data['sun_price'];
                    }else{
                        $price = $data['price'];
                    }
                }
//                $day_temp[] = ['day'=>$day,'price'=>(int)$price,'stamp'=>$month_start*1000,'week'=>$week];
                $day_temp[] = ['day'=>$day,'price'=>$price,'stamp'=>$month_start*1000,'week'=>$week];
                $month_start = strtotime("+1 day",$month_start);
            }
            $temp['day'] = $day_temp;
            $list_data[] = $temp;
            $today = strtotime("+1 month",$today);
        }
        return $list_data;
    }
}
